package com.itcam.interview.pro01javase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class Demo06ListRemoveDuplicates {
    public static void main(String[] args) {
//        method1();
//        method2();
//        method3();
//        method4();

        List<Integer> oldList = Arrays.asList(50, 45, 45, 45, 4, 4, 4, 3);
        List<Integer> midList = new ArrayList<>(oldList);
        List<Integer> newList = new ArrayList<>(oldList);

        for (int i = 0; i < newList.size() - 1; i++) {
            for (int j = newList.size() - 1; j > i; j--) {
                if (newList.get(j).equals(newList.get(i))) {
                    newList.remove(j);
                }
            }
        }

        newList.forEach(s -> System.out.print(s + " "));

    }

    /**
     * 循环坐标去除重复，类似双指针，按照值找到下标
     * 如果下标不同，表示有重复需要删除
     */
    private static void method4() {
        List<Integer> oldList = Arrays.asList(50, 45, 45, 45, 4, 4, 4, 3);
        List<Integer> midList = new ArrayList<>(oldList);
        List<Integer> newList = new ArrayList<>(oldList);

        for (Integer element : midList) {
            if (newList.indexOf(element) != newList.lastIndexOf(element)) {
                newList.remove(newList.lastIndexOf(element));
            }
        }

        newList.forEach(s -> System.out.print(s + " "));
    }

    /**
     * stream流
     */
    private static void method3() {
        List<Integer> oldList = Arrays.asList(50, 45, 45, 45, 4, 4, 4, 3);
        List<Integer> midList = new ArrayList<>(oldList);
        List<Integer> newList = new ArrayList<>();

        newList = midList.stream()
                .distinct()
                .collect(Collectors.toList());

        newList.forEach(s -> System.out.print(s + " "));
    }

    /**
     * 引用hashset
     */
    private static void method2() {
        List<Integer> oldList = Arrays.asList(50, 45, 45, 45, 4, 4, 4, 3);
        List<Integer> newList = new ArrayList<>(new HashSet<>(oldList));
        newList.forEach(s -> System.out.print(s + " "));
    }

    private static void method1() {
        List<Integer> oldList = Arrays.asList(50, 45, 45, 45, 4, 4, 4, 3);
        List<Integer> midList = new ArrayList<>(oldList);
        List<Integer> newList = new ArrayList<>();

        for (int i = 0; i < oldList.size(); i++) {
            Integer temp = midList.get(i);
            if (!newList.contains(temp)) {
                newList.add(temp);
            }
        }
        System.out.println(newList);
    }
}
